Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

290
Vistas
Firefox and Google Chrome differences creating or sorting an array using .sort(() => Math.random() - 0.5);

I'm trying to make a minesweeper, and something weird has happened, in Chrome or Chromium-based navigators everything seems and works just fine, but in firefox, all of the bombs generated clumped together at the end, or the start of the array, is there any difference in how sort() works with parameters?

I'll leave the piece of the code that generates the board.

  

    function createBoard() {
        //create an array with shuffled bombs
        const bombsArray = Array(bombAmount).fill("bomb");
        const emptyArray = Array(width * width - bombAmount).fill("valid");
        const gameArray = emptyArray.concat(bombsArray);
        const shuffledArray = gameArray.sort(() => Math.random() - 0.5);
        for (let i = 0; i < width * width; i++) {
          const square = document.createElement("div");
          square.setAttribute("id", i);
          square.classList.add(shuffledArray[i])
          grid.appendChild(square);
          squares.push(square);

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

From the documentation:

Note: compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments.

In your case, you don't do this, which gives undefined behaviour, most likely dependent on the sorting algorithm that is used by the browser's Array.sort implementation.

You can ensure that the random value for a particular array item remains stable by mapping to a new array with a random order property, sorting, then mapping back again:

const shuffledArray = gameArray
  .map((value) => ({ value, order: Math.random() }))
  .sort((a, b) => a.order - b.order)
  .map(({ value }) => value)

This probably isn't the most efficient way of shuffling an array, but a minesweeper board is so small that it won't matter.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda